package com.example.service.impl;

import com.example.mapper.baseComponentMapp;
import com.example.pojo.baseComponentPojo;
import com.example.pojo.productModelListPojo;
import com.example.service.baseComponentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * ClassName:baseComponentImpl
 * Description:
 *
 * @Author 赵永峰
 * @Create 2024/7/11 14:39
 * @Version 1.0
 */
@Service
@Slf4j
public class baseComponentImpl implements baseComponentService {
    @Autowired
    private baseComponentMapp baseComponentMapp;
    @Value("${file.upload-dir}")
    private String saveDir;
    //插入一条新的记录
    public void insertOne(baseComponentPojo baseComponent){
        baseComponent.setEstablishTime(LocalDateTime.now());
        baseComponent.setUpdateTime(LocalDateTime.now());
        baseComponentMapp.insertOne(baseComponent);
    }
    //查询所有的数据
    public List<baseComponentPojo> queryAll(){
        List<baseComponentPojo> baseComponentPojoList=baseComponentMapp.queryAll();
        return baseComponentPojoList;
    }
    //对零部件信息进行编辑
    public void editOne(baseComponentPojo baseComponent){
        //组合时间
        baseComponent.setUpdateTime(LocalDateTime.now());
        baseComponentMapp.editOne(baseComponent);
    }
    //筛选出最新写入的数据,利用的是Id最大筛选
    public baseComponentPojo queryByIdMax(){
        baseComponentPojo baseComponentPojo=baseComponentMapp.queryByIdMax();
        return baseComponentPojo;
    }
    //辅助函数：对零部件信息进行调用,调用所有的信息
    public List<productModelListPojo> inquiryProductListBaseComponentAll(){
        List<productModelListPojo> pojos=baseComponentMapp.inquiryProductList();
        return pojos;
    }

    //下载文件
    public byte[] readFile(String fileName){
        File file = new File(saveDir + fileName);
        // 检查文件是否存在且可读
        if (file.exists() && file.canRead()) {
            try (FileInputStream fis = new FileInputStream(file)) {
                // 读取文件内容到byte[]数组中
                byte[] fileContent = fis.readAllBytes();
                return fileContent; // 返回文件内容的byte[]数组
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 如果文件不存在或不可读，或者读取时发生异常，返回null
        System.out.println("文件不存在或不可读：" + file.getAbsolutePath());
        return null;
    }
}
